import Vue from 'vue'
const ROTATE_DEG = 25; //旋转角度
const RADIAN_BASE = Math.PI / 180; //弧度基数
const H_SPANCE = 160; // 水印水平间距
const V_SPANCE = 140; // 上下间距

Vue.directive('watermark', (el, binding) => {
  function addWaterMarker(text, parentNode, font, textColor) {// 水印文字，父元素，字体，文字颜色
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    context.font = '400 12px Microsoft YaHei, Arial, PingFang SC, Helvetica';
    // 测量出文字的宽度，来确定画布的宽度
    const textWidth = context.measureText(text).width + 60;
    const contentWidth = textWidth * Math.cos(ROTATE_DEG * RADIAN_BASE) + H_SPANCE;
    const contentHeight = textWidth * Math.sin(ROTATE_DEG * RADIAN_BASE) + V_SPANCE;
    canvas.width = contentWidth;
    canvas.height = contentHeight;
    // 画布大小改变后，样式需要重新设置
    context.font = font || '400 12px Microsoft YaHei, Arial, PingFang SC, Helvetica';
    context.textAlign = 'center';
    context.fillStyle = textColor || 'rgba(219,219,219,0.6)';
    context.textBaseline = 'middle';
    context.letterSpacing = '0.2px';
    const centerPoint = { x: contentWidth / 2, y: contentHeight / 2 };
    context.translate(centerPoint.x, centerPoint.y);
    context.rotate(-ROTATE_DEG * (Math.PI / 180));
    context.fillText(text, canvas.width / 8, canvas.height / 2);
    parentNode.style.backgroundImage = "url(" + canvas.toDataURL("image/png", 1) + ")";
  }
  addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
})
